<template>
	<div class="home-screen-module6" ref="content">
		<div class="chart-box" :id="chartid"></div>
	</div>
</template>

<script setup>
import { ref, onBeforeUnmount, toRefs, getCurrentInstance, onMounted } from 'vue';
import * as echarts from 'echarts';
import { markRaw } from 'vue'
import { eleResize } from '@/assets/js/utils'

const instance = getCurrentInstance()
const props = defineProps({
	dataSource:{
		type:Array,
		default:function(){
			return []
		}
	}
})
const {dataSource} = toRefs(props)

let $frame = null;
let myChart = null;
const chartid = ref('home6-chart-'+new Date().getTime())
const defaultOption = {
	tooltip: {
		trigger: 'axis'
	},
	legend:{
		show:true,
		textStyle:{
			color:'#fff'
		},
		top:'3%'
	},
	grid: {
		left: 10,
		right: 15,
		bottom: 55,
		containLabel: true
	},
	xAxis: {
		data: [],
		axisLine:{
			lineStyle:{
				color:'#fff'
			}
		}
	},
	yAxis: {
		axisLine:{
			lineStyle:{
				color:'#fff'
			}
		}
	},
	dataZoom: [
		{
			startValue: '2014-06-01',
			type: 'slider'
		}
	],
	series: [
		{name:'出库单',type:'bar',data:[]},
		{name:'入库单',type:'bar',data:[]}
	]
}

const createChart = function(){
	if (!myChart) {
		myChart = markRaw(echarts.init(window.document.getElementById(chartid.value)))
	}
}

const drawChart = function(){
	if (dataSource.value.length<=0) return false;
	let opt =  JSON.parse(JSON.stringify(defaultOption))
	if (dataSource.value.length<=7) {
		opt.grid.bottom = 15
		delete opt.dataZoom;
	} else {
		opt.dataZoom[0].startValue = dataSource.value[dataSource.value.length-1].dateStr
	}
	for (let i=dataSource.value.length-1;i>=0;i--) {
		opt.xAxis.data.push(dataSource.value[i].dateStr)
		opt.series[0].data.push(dataSource.value[i].outboundOrder)
		opt.series[1].data.push(dataSource.value[i].receiptDoc)
	}
	destoryChart()
	createChart()
	myChart.setOption(opt)
}

const destoryChart = function(){
	try{
		myChart.dispose();
		window.document.getElementById(chartid.value).innerHTML = '';
		myChart = null;
	}catch(e){
		//TODO handle the exception
	}
}

/* 创建div宽高变化监听器 */
const createEleResize = function(){
	$frame = instance.refs.content;
	eleResize.on($frame, drawChart);
}

/* div宽高变化事件移除 */
const destroyEleResize=function(){
	try{
		eleResize.off($frame, drawChart);
		$frame = null
	}catch(e){
		//TODO handle the exception
	}
}

onMounted(()=>{
	createEleResize()
})

onBeforeUnmount(()=>{
	destroyEleResize()
	destoryChart()
	createChart()
})

defineExpose({drawChart})
</script>

<style lang="scss" scoped>
.home-screen-module6{
	height: 100%;
	.chart-box{
		height: 100%;
	}
}
</style>